package com.gjy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gjy.domain.File;
import com.gjy.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器，实现基于Web的文件上传，文件下载，浏览文件信息
 * </p>
 *
 * @author 宫静雨
 * @since 2021-12-23
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private Logger logger = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileService fileService;

    /**
     * 返回文件源数据信息
     * url = http://localhost:8080/file/getInfo?uuid=
     * @param uuid 传入的参数，唯一标识
     * @return 返回文件的元数据
     */
    @GetMapping("/getInfo")
    public File getInfo(@RequestParam String uuid) {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        File file = fileService.getOne(queryWrapper);
        logger.info("file --> {}", file);
        return file;
    }

    /**
     * 实现文件下载功能
     * url:http://localhost:8080/file/get?uuid=
     * @param uuid     传入的参数，唯一标识
     * @return 返回流
     * @throws IOException 运行错误抛出异常
     */
    @GetMapping("/get")
    public ResponseEntity<InputStreamResource> get(@RequestParam String uuid) throws IOException {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        File file = fileService.getOne(queryWrapper);

        if (null == file) {
            return ResponseEntity.notFound().build();
        }

        String dir = file.getDir();
        String type = file.getType();
        String fileUuid = file.getUuid();

        Path path = Paths.get("D:\\file", dir, fileUuid + "." + type);
        logger.info("文件下载路径 --> {}", path);

        FileSystemResource a = new FileSystemResource(path);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + fileUuid + "." + type);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(a.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(a.getInputStream()));
    }

    /**
     * 实现文件上传功能
     * url = http://localhost:8080/file/upload
     * Windows 默认目录为：D:\\file\\
     * Linux,Mac 默认目录为：/file/
     * @param files 文件
     * @return 文件的唯一标识 UUID
     */
    @PostMapping("/upload")
    public List<String> upload(MultipartFile[] files) {
        List<String> list = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                String uuid = UUID.randomUUID().toString();
                logger.info("uuid --> {}", uuid);
                File myFile = new File();
                long size = file.getSize();
                String filename = file.getOriginalFilename();
                assert filename != null;
                String[] split = filename.split("\\.");
                String oldFileName = split[0];
                LocalDateTime creation = LocalDateTime.now();
                String dir = "" + creation.getYear() + creation.getMonthValue() + creation.getDayOfMonth();
                myFile.setId(null);
                myFile.setUuid(uuid);
                myFile.setSize(String.valueOf(size));
                myFile.setType(split[1]);
                myFile.setName(oldFileName);
                myFile.setCreation(creation);
                myFile.setDir(dir);
                logger.info("上传的文件 --> {}", myFile);

                if (System.getProperty("os.name").contains("dow")) {
                    if (!Files.exists(Paths.get("D:\\file", dir))) {
                        Files.createDirectories(Paths.get("D:\\file", dir));
                    }
                    list.add(uuid);

                    file.transferTo(Paths.get("D:\\file", dir, uuid + "." + split[1]));
                } else if (System.getProperty("os.name").equalsIgnoreCase("linux")
                        || System.getProperty("os.name").equalsIgnoreCase("mac")) {
                    if (!Files.exists(Paths.get("/file/", dir))) {
                        Files.createDirectories(Paths.get("/file/", dir));
                    }
                    list.add(uuid);

                    file.transferTo(Paths.get("/file/", dir, uuid + "." + split[1]));
                }

                fileService.save(myFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}